const fs = require('fs');
const path = require('path');
const lodash = require('lodash');
const { ls } = require('shelljs');
const inquirer = require('inquirer');
const log = require('../utils/log');
const { isComponentNameValid } = require('./utils');

function checkTemplate(templateName) {
  return new Promise((resolve, reject) => {
    // 先找是否有该模板
    const p = path.join(
      global.appRoot,
      `./templates/${templateName}/index-mobx.hbs`
    );
    const isExsited = fs.existsSync(p);
    if (!isExsited) {
      log.error(`${templateName} not exsit!!`);
      // TODO: 这里重新输入改成promps 让他自己选
      log.warn('These templates you can use');
      ls(path.join(global.appRoot, './templates/')).forEach((li) => {
        console.log(`${li}\n`);
      });
      reject();
    }
    resolve(1);
  });
}

const selectTemplate = () => {
  const templates = ls(path.join(global.appRoot, './hbs/')).filter(
    // const templates = ls(path.join(global.appRoot, './templates/')).filter(
    (key) => !key.includes('_')
  );
  return inquirer.prompt([
    {
      name: 'template',
      type: 'list',
      message: 'choose your template',
      choices: templates,
      default: templates[0],
    },
    {
      name: 'componentName',
      type: 'input',
      message: 'input component name',
      default: `MyComponent${Math.floor(Math.random() * 100)}`,
      validate: (str) => {
        if (!isComponentNameValid(str)) return '组件名首字母大写且不得包含中文';
        return true;
      },
    },
  ]);
};

module.exports = selectTemplate;
